package 栈;

import java.util.ArrayDeque;
import java.util.Deque;
/*字符串解码 2[a3[c]] 解码为 acccaccc
* 思路设置两个栈帧，一个存储字符串，一个存储数字，并根据情况来进行分别的讨论
* 细节：为避免空栈，字符串栈先压入一个空字符串*/
public class 字符串解码 {

    public String solution(String ss)
    {
       Deque<StringBuffer> st = new ArrayDeque<>();
       Deque<Integer> num = new ArrayDeque<>();
       StringBuffer sb = new StringBuffer();
       st.push(sb.append(' '));
       char [] s = ss.toCharArray();
       int i = 0, n = s.length;
       while(i < n)
       {

           if(s[i] >='0' && s[i]<='9')
           {
               int tmp = 0;
               while(i<n && s[i] >='0' && s[i]<= '9')
               {
                   tmp = tmp*10+(s[i]-'0');
                   i++;
               }
               num.push(tmp);
           }
           else if(s[i]=='[')
           {
               i++; //把后面的字符串提取出来
               StringBuffer tmp = new StringBuffer();
               while(i<n && s[i]!=']')
               {
                   tmp.append(s[i]);
                   i++;
               }
               st.push(tmp);
           }else if(s[i]==']')
           {
                StringBuffer tmp = st.pop();
                int k = num.pop();

                while( k-- !=0)
                {
                    st.peek().append(tmp);
                }
                i++;
           }else
           {
               StringBuffer tmp = new StringBuffer();
               while(i<n && s[i]>='a' && s[i]<='z')
               {
                   tmp.append(s[i]);
                   i++;
               }
               st.peek().append(tmp);
           }
       }
       return  st.peek().toString();
    }
}
